package org.jet.emall.security.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jet.emall.rbac.po.AdminUserView;
import org.jet.emall.rbac.service.mp.IAdminUserViewService;
import org.jet.emall.security.model.GrantedAuthorityModel;
import org.jet.emall.security.model.UserDetailsModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-07 19:45
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IAdminUserViewService adminUserViewService;


    /**
     * 根据用户名将用户信息加载出来，包装成UserDetails对象交给spring-security框架
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Wrapper<AdminUserView> wrapper = new QueryWrapper<>();
        ((QueryWrapper<AdminUserView>) wrapper).eq("username",username);
        AdminUserView adminUserView = adminUserViewService.getOne(wrapper);
        UserDetailsModel user = new UserDetailsModel();
        user.setId(adminUserView.getId())
        .setUsername(adminUserView.getUsername())
        .setPassword(adminUserView.getPassword())
        .setRoleId(adminUserView.getRoleId())
        .setStatus(adminUserView.getStatus())
        .setRoleName(adminUserView.getRoleName());
        GrantedAuthorityModel grantedAuthorityModel = new GrantedAuthorityModel();
        grantedAuthorityModel.setAuthority(adminUserView.getRoleName());
        Collection<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(grantedAuthorityModel);
        user.setGrantedAuthorities(grantedAuthorities);
        return user;
    }
}
